﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Xml.Schema;

namespace OurServices.BankServices
{
    class Student
    {
        public string Name { get; set; }
        public string Phone { get; set; }
    }
    public class StudentXML
    {
        public static List<string> GetStudents()
        {
            List<string> studs = new List<string>();
            var studsXML = ValidateAndLoadStudentXML();

            //var st = studsXML.Element("Students").Elements("Student").Where(
            //    s => s.Attribute("Type").Value.Equals("External")).Elements("Name").Select(s => s.Value).ToList();

            var st = studsXML.Element("Students").Elements("Student").Where(
                s => s.Attribute("Type").Value.Equals("External")) //.Select(s=>s.Elements("Name").ToList());
                .Descendants();
            var v = (from s in st
                     select new Student
                                {
                                    Name = s.Element("Name").Value,
                                    Phone = s.Element("Phone").Value,
                                }).ToList();
           

            return studs;
        }

        private static XDocument ValidateAndLoadStudentXML()
        {
            XDocument xDocument = null;
            if (HttpContext.Current != null)
            {
                xDocument = (XDocument)HttpRuntime.Cache.Get("StudentXML");
            }
            if (xDocument == null)
            {
                XmlSchemaSet schemas = new XmlSchemaSet();

                string docPath = @"D:\Student\UTPL\WCFWebHostings\OurServices\BankServices\Student.xml";
                string schemaPath = @"D:\Student\UTPL\WCFWebHostings\OurServices\BankServices\Student.xsd";

                schemas.Add(string.Empty, schemaPath);

                xDocument = XDocument.Load(docPath);
                //}
                //return xDocument;

                bool errors = false;
                string exceptionMessage = "Invalid Configuration.";

                xDocument.Validate(schemas, (o, e) =>
                 {
                     exceptionMessage = exceptionMessage + " " + e.Exception.Message;
                     errors = true;
                 });
                if (errors)
                    throw new Exception(exceptionMessage);
                else
                    CacheConfigurationDocument("StudentXML", docPath, xDocument);
            }
            return xDocument;
        }
        private static void CacheConfigurationDocument(string name, string fileName, XDocument xDocument)
        {
            HttpRuntime.Cache.Add(name, xDocument, new System.Web.Caching.CacheDependency(fileName), DateTime.Now.AddDays(7),
            TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
        }
    }
}